<?php

namespace App\Common;


use App\X\EHelper;
use App\X\XContext;
use EasySwoole\EasySwoole\ServerManager;
use XWX\Common\H;

class Log
{
    /**
     * log
     *
     * @param type $method __METHOD__
     * @param type $msg msg
     * @param int $level LOG_INFO, LOG_WARNING, LOG_DEBUG(default)
     * @throws \Exception
     */
    static function funcLog($method = null, $msg = null, $level = LOG_DEBUG)
    {
        if (H::funcStrIsNullOrEmpty($method))
        {
            //报错
            throw new \Exception('method is miss');
        }


        if ($level == LOG_DEBUG)
        {
            //正式环境 debug日志不记录
            if (EHelper::funcGetConf('SYS.log_debug_show') == 0)
            {
                return;
            }
        }


        if (is_string($msg))
        {
            $msg_log = "[$method] $msg";
        }
        else if (is_array($msg))
        {
            $cnt = count($msg);
            if ($cnt > 0)
            {
                $msg_log = "[$method] " . H::funcToStr($msg);
            }
            else
            {
                $msg_log = "[$method] ...";
            }
        }
        else if ($msg == null)
        {
            $msg_log = "[$method]";
        }
        else
        {
            $msg_log = "[$method] ...";
        }

        $level_str = '[DEBUG]';
        switch ($level)
        {
            case LOG_INFO:
                $level_str = '[INFO]';
                break;
            case LOG_WARNING:
                $level_str = '[WARNING]';
                break;
            case LOG_ERR:
                $level_str = '[ERROR]';
                break;

            case 288:
                $level_str = '[TASK]';
                break;
        }

        $worker_id = ServerManager::getInstance()->getSwooleServer()->worker_id;
        $cid = XContext::funcInsStatic()->getCoroutineID();

        $string = "[w{$worker_id}][{$cid}]{$msg_log}";


        go(function () use ($level_str, $string)
        {
            \EasySwoole\EasySwoole\Logger::getInstance()->console($string, 2, $level_str);
            \EasySwoole\EasySwoole\Logger::getInstance()->onLog()->set('log_after', function ($msg, $logLevel, $level_str)
            {
                //记录mongodb
            });
        });
    }


    static function funcLogDebug($method = null, $msg = null)
    {
        self::funcLog($method, $msg, LOG_DEBUG);
    }

    static function funcLogInfo($method = null, $msg = null)
    {
        self::funcLog($method, $msg, LOG_INFO);
    }

    static function funcLogErr($method = null, $msg = null)
    {
        self::funcLog($method, $msg, LOG_ERR);
    }

    static function funcLogTask($method = null, $msg = null)
    {
        self::funcLog($method, $msg, 288);
    }
}